Skip to content
Go back

现代 Git 特性的推荐命令方案

Published:  at  08:42 PM

一、基础操作

1. 分支管理

# 创建并切换分支(推荐)
git switch -c <new-branch>      # 替代 checkout -b

# 切换分支
git switch <existing-branch>   # 替代 checkout

# 快速回到上一个分支
git switch -                   # 等效于 checkout -

# 查看本地和远程分支
git branch -av

2. 提交与暂存

# 提交(带描述)
git commit -m "feat: 添加用户认证" --no-verify  # 跳过钩子

# 追加修改到上一个提交
git commit --amend --no-edit

# 暂存(带描述)
git stash push -m "work in progress"

# 恢复最近一次stash
git stash pop

二、代码集成

1. 拉取远程更新

# 安全拉取(避免自动合并)
git fetch
git rebase origin/main         # 推荐:变基模式

# 或简化为(自动rebase)
git pull --rebase

2. 分支合并

# 推荐:使用squash合并(保持线性提交历史)
git switch main
git merge --squash <feature-branch>

# 合并冲突时(保留修改)
git rebase --continue

三、撤销与重置

1. 撤销未提交修改

# 丢弃工作区修改
git restore <file>             # 替代 checkout -- <file>

# 丢弃所有未提交修改
git restore .

2. 回退提交

# 软重置(保留修改)
git reset --soft HEAD~1

# 硬重置(丢弃提交)
git reset --hard <commit-hash>

四、远程协作

1. 推送分支

# 创建并推送新分支
git push -u origin <new-branch>

# 强制推送(谨慎使用)
git push --force-with-lease    # 更安全的强制推送

2. 删除分支

# 删除本地分支
git branch -d <branch>

# 删除远程分支
git push origin --delete <branch>

五、高级技巧

1. 工作树(多分支并行开发)

# 创建新工作树
git worktree add ../feature-work feature

# 删除工作树
git worktree remove ../feature-work

2. 交互式变基

# 合并最近3个提交
git rebase -i HEAD~3

3. 选择性 cherry-pick

# 从其他分支 cherry-pick 特定提交
git cherry-pick <commit-hash>

六、别名配置(提升效率)

.gitconfig 中添加:

[alias]
  co = switch
  cob = switch -c
  st = status -sb
  lg = log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit
  amend = commit --amend --no-edit
  wip = commit -m "WIP"
  undo = reset --soft HEAD~1
  pop = stash pop
  sync = pull --rebase && push

七、推荐工作流

1. 功能开发流程

# 1. 创建新分支
git switch -c feature/new-auth

# 2. 开发并提交
git add .
git commit -m "feat: 添加用户认证"

# 3. 同步主分支更新
git fetch
git rebase origin/main

# 4. 推送并创建PR
git push -u origin feature/new-auth

2. 紧急修复流程

# 1. 创建hotfix工作树
git worktree add ../hotfix-1.0.1 main

# 2. 在新目录修复并提交
cd ../hotfix-1.0.1
git commit -m "fix: 修复支付漏洞"

# 3. 推送并合并
git push origin main

八、安全注意事项

  1. 避免强制推送:优先使用 --force-with-lease 替代 --force

    The —force-with-lease option provides a safer alternative to —force. It checks whether the remote branch points to the same commit as your local copy. If it doesn’t, because someone else has pushed changes, the operation will be aborted, protecting other collaborators’ work

  2. 慎用硬重置git reset --hard 会永久丢失数据。

  3. 提交前同步git pull --rebase 保持线性提交历史。

  4. 使用工作树:避免频繁切换分支,减少冲突风险。

九、推荐工具链


Suggest Changes

Previous Post
ThreadPoolExecutor的重要特性和概念
Next Post
JPA的1+N问题